package com.wlyuan.open.scanner.domain.message;

import com.alibaba.fastjson.JSON;
import com.wlyuan.open.scanner.constant.Constants;
import com.wlyuan.open.scanner.constant.TableEnum;
import lombok.extern.slf4j.Slf4j;
import lombok.var;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
@Slf4j
public class BuildAutoIdColumn {

    /**
     * 构建主键id
     *
     * @param tableName
     * @param data
     * @return
     */
    public static Long build(String tableName, String data) {
        String column = Optional.ofNullable(TableEnum.fromName(tableName)).map(TableEnum::getAutoIdColumn).orElse(null);
        if (Objects.isNull(column)) {
            logger.error("{}未指定主键id列", tableName);
            return null;
        }
        var map = JSON.parseObject(data, Map.class);
        var autoId = map.get(build(tableName, column, map));
        return Optional.ofNullable(autoId).map(x -> Long.valueOf(String.valueOf(x))).orElse(null);
    }

    private static String build(String tableName, String column, Map<String, Object> map) {
        //地址表时，特殊处理，需要处理线上，线下承运方id
        if (TableEnum.isAddr(tableName)) {
            if (Objects.nonNull(map.get(Constants.ADDR_SUPPLIER_ID))) {
                //supplierId 字段
                return Constants.ADDR_SUPPLIER_ID;
            }
            if (Objects.nonNull(map.get(Constants.ADDR_SYMBOL_ID))) {
                //symbolId 字段
                return Constants.ADDR_SYMBOL_ID;
            }
        }
        return column;
    }
}
